#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <ctime>
using namespace std;


//每个线程执行对应累加操作
////////////////////////////////////////////
#define NUM 10
//线程执行状态
enum{OK,ERROR};
//创建线程void* args传对象
class ThreadData
{
public:
    ThreadData(const string& name,int id,time_t createTime,int top)
    :_name(name)
    ,_id(id)
    ,_createTime((uint64_t)createTime)
    ,_status(OK)
    ,_top(top)
    ,_result(0)
    {}
     ~ThreadData()
    {}
public:
    //输入的
    string _name;
    int _id;
    uint64_t _createTime;
    // 返回的
    int _status;
    int _top;//
    int _result;//执行结果
    //char arr[n]
};


void* thread_run(void* args)
{
    //char* name=(char*)args;
    ThreadData* td=static_cast<ThreadData *>(args);
    //每一个线程做对应的计算
    for(int i=1;i<=td->_top;i++)
    {
        td->_result+=i;
    }
    cout << td->_name << " cal done!" << endl;
    
    pthread_exit(td);
    // while(true)
    // {
    // //cout<<"new thread running,thread name:"<<name<<endl;
    // cout<<"new thread running,thread name:"<<td->_name<<"create time:"<<td->_createTime<<"index:"<<td->_id<<endl;
    
    // sleep(4);
    // //exit()进程终止不是线程终止
    // break;
    // }
    // delete td;
    // pthread_exit((void*)true);
    // // return nullptr;
}

int main()
{
    pthread_t tids[NUM];
    for(int i=0;i<NUM;i++)
    {
        char* tname=new char[64];
        snprintf(tname,64,"thread-%d",i+1);
        ThreadData* td=new ThreadData(tname,i+1,time(nullptr),100+5*i);
        pthread_create(tids+i,nullptr,thread_run,td);
        sleep(1);
    }
    // sleep(3);
    void* ret=nullptr;
    for(int i=0;i<NUM;i++)
    {
        int n=pthread_join(tids[i],&ret);
        if(n!=0) cerr<<"pthread_join error"<<endl;

        //cout<<"thread quit:"<<(bool)ret<<endl;
        ThreadData *td = static_cast<ThreadData *>(ret);
        if(td->_status == OK)
        {
            cout << td->_name << " 计算的结果是: " << td->_result 
            << " (它要计算的是[1, " << td->_top << "])" <<endl;
        }
        delete td;
    }
    cout<<"all thread quit"<<endl;
    return 0;
    
    // while (true)
    // {
    //     cout<<"main thread running,new thread id:"<<endl;
    //     sleep(1);
    // }
    

}
